package com.note.backend.service.impl.user.account;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.note.backend.mapper.UserMapper;
import com.note.backend.pojo.User;
import com.note.backend.service.user.account.RegisterService;
import com.note.backend.utils.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.time.LocalDateTime;

@RequiredArgsConstructor
@Service
public class RegisterServiceImpl implements RegisterService {

    private final UserMapper userMapper;


    private final PasswordEncoder passwordEncoder;

    @Override
    public Result register(String username, String password, String confirmPassword) {
        if (username == null) {
            return Result.error("用户名不能为空");
        }

        if (password == null || confirmPassword == null) {
            return Result.error("密码不能为空");
        }

        username = username.trim();
        if (username.isEmpty()) {
            return Result.error("用户名不能为空");
        }

        if (password.isEmpty() || confirmPassword.isEmpty()) {
            return Result.error("密码不能为空");
        }

        if (username.length() > 100) {
            return Result.error("用户名长度不能大于100");
        }

        if (password.length() > 100 || confirmPassword.length() > 100) {
            return Result.error("密码长度不能大于100");
        }

        if (!password.equals(confirmPassword)) {
            return Result.error("两次输入的密码不一致");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        List<User> users = userMapper.selectList(queryWrapper);

        if (!users.isEmpty()) {
            return Result.error("用户名已存在");
        }

        //满足以上的条件 添加新用户
        String encodedPassword = passwordEncoder.encode(password);
        String photo = "https://www.helloimg.com/i/2025/04/01/67eb695c5ffa7.jpg";
        User user = new User(null, username, encodedPassword, photo,LocalDateTime.now(), LocalDateTime.now());
        userMapper.insert(user);
        return Result.success();
    }
}